//
//  Singleton.m
//  TengyunStation
//
//  Created by Johnny on 15/8/21.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "Singleton.h"
#import "Reachability.h"
#import "TSHeader.h"

static Singleton *_singleton = nil;
@implementation Singleton

+ (Singleton *)shareInstance {
    if (!_singleton) {
        _singleton = [[Singleton alloc] init];
    }
    return _singleton;
}

- (id)init {
    self = [super init];
    if (self) {
        NSArray *array = [Usermessage findAll];
        if (array.count > 0) {
            self.userMessage = [array firstObject];
        }
        NSArray *array1 = [CityModel findAll];
        if (array1.count > 0) {
            self.cityModel = [array1 firstObject];
        }
        [self startNewworkCheck];
    }
    return self;
}

- (void)setCityModel:(CityModel *)cityModel {
    _cityModel = cityModel;
    [CityModel clearTable];
    [cityModel save];
}

- (void)startNewworkCheck {
    [[Reachability reachabilityWithHostname:@"www.baidu.com"] startNotifier];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
}

- (void)reachabilityChanged:(NSNotification *)notification {
    Reachability *curReach = [notification object];
    NetworkStatus status = [curReach currentReachabilityStatus];
    if (status == NotReachable) {
        self.isHadNetwork = NO;
    } else {
        self.isHadNetwork = YES;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:NetworkCheckNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}

@end
